package licode.unisop.auth.infrastructure.service;

import licode.unisop.provider.api.SiLocker;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用JAVA机制实现本地锁
 *
 * @author licode
 * @version 1.0
 * @date 2017-02-01 7:42
 */
@Component
public class SiLockerDef implements SiLocker {
    static class LockerDef implements Locker {
        private final ReentrantLock lock;

        public LockerDef(boolean fair) {
            lock = new ReentrantLock(fair);
        }

        @Override
        public void lock(long timeout) {
            lock.lock();
        }

        @Override
        public boolean tryLock(long wait, long timeout) {
            try {
                return lock.tryLock(wait, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                return false;
            }
        }

        @Override
        public void unlock() {
            lock.unlock();
        }
    }

    @Override
    public Locker getLocker(String lockerId) {
        return new LockerDef(false);
    }

    @Override
    public Locker getFairLocker(String lockerId) {
        return new LockerDef(true);
    }
}
